<?php
/**
 * Class to help generate file for component
 * @author	muinx
 */

//require language helper
require_once('language.helper.php');

class GenerateHelper
{
	protected $rootPath;
	protected $component;
	
	/**
	 * Construct, init some vars
	 * @param Int $componentId	Component ID
	 */
	function __construct($componentId)
	{
		//get component
		$this->component = $this->getRecord('#__gencode_components', $componentId);
		
		//get component name
		$comName = str_replace(' ', '_', strtolower('com_'.$this->component->name));
		
		//define component path
		$this->rootPath = JPATH_ROOT . DS . 'tmp' . DS . 'com_gencode' . DS . $comName . DS;
	}
	
	/**
	 * Create folders for component
	 */
	protected function createFolder()
	{
		$root = $this->rootPath;
		
		$folders = array(
							'controllers',
							'helpers',
							'html',
							'html' . DS . 'css',
							'html' . DS . 'images',
							'html' . DS . 'js',
							'language',
							'models',
							'models' . DS . 'fields',
							'models' . DS . 'forms',
							'sql',
							'tables',
							'views',
					);
		$pathnameAdmin = $root . 'admin' . DS;
		$pathnameFront = $root . 'site' . DS;
		
		if(!is_dir($pathnameAdmin))
			mkdir($pathnameAdmin, 0777, true);
			
		if(!is_dir($pathnameFront))
			mkdir($pathnameFront, 0777, true);
		
		//create folder
		foreach ($folders as $folder)
		{
			if(!is_dir($pathnameAdmin . $folder . DS))
				mkdir($pathnameAdmin . $folder . DS, 0777, true);
				
			if(!is_dir($pathnameFront . $folder . DS))
			{
				if(in_array($folder, array('models' . DS . 'fields', 'models' . DS . 'forms', 'sql', 'tables', 'language')))
					continue;
				
				mkdir($pathnameFront . $folder . DS, 0777, true);
			}
				
		}
	}
	
	/**
	 * Function to build files for backend and front
	 * @return component name
	 */
	function buildFiles()
	{
		$db = JFactory::getDbo();
		
		$component = $this->component;		
		
		//process to get component prefix
		$componentPrefix = str_replace(' ', '_', ucwords($component->name));		
		
		//get models
		$query = $db->getQuery(true);
		
		/**
		 * Select model backend to prepare gen code
		 */
		$query->select('m.*, t.name AS table_name, model_form.name as model_form_name');
		$query->from('#__gencode_genms m');
		
		$query->join('INNER', '#__gencode_gendbs t ON m.table_id = t.id');
		$query->join('LEFT', '#__gencode_genms model_form ON m.model_form_id = model_form.id');
		
		$query->where('m.state >= 0 AND m.component_id = ' . $component->id);
		
		$db->setQuery($query);
		$rs = $db->loadObjectList();
		
		//create component folder to store files
		self::createFolder('com_' . str_replace(' ', '_', strtolower($component->name)));
				
		/**
		 * 
		 * @var object, language helper
		 */
		$language = new LanguageHelper();
		
		//create sys language file
		$this->createSysBackendLanguage(null, false);
		
		//create language file
		$this->createBackendLanguage(null, false);
		
		//define default view to set default view in controller
		$defaultView = array();
		$defaultViewEdit = array();
		
		/**
		 * Loop for list of backend model to create backend models, views
		 */
		foreach ($rs as $key => $m)
		{
			$languageContent = '';
			
			$search[] = array();
			$replace[] = array();
			
			//init var
			$name 		= $m->name;
			$type 		= $m->type;
			$modelForm 	= $this->getRecord('#__gencode_genms', $m->model_form_id);
			
			//create controllers
			self::createBackendController($name, $type, $modelForm);
			
			//create models
			self::createBackendModel($m, $type);
			
			//create views
			self::createBackendView($m, $type);
			
			/**
			 * if model type is list, then create language for list
			 */
			if($type == 'list')
			{
				$defaultView[] = $filename = str_replace(' ', '_', strtolower($m->name));
				
				//create backend language for list
				$search = array('#xs#', '#X_with_s#', '#XS#');
				$replace = array($m->name, ucfirst($m->name), strtoupper($filename));
				
				$languageContent  = LanguageHelper::getMessages();
				
				$languageContent = str_replace($search, $replace, $languageContent);
				
				$this->createBackendLanguage($languageContent);
			}
			/**
			 * else, create language for form
			 */
			else
			{
				//create backend language for form
				$search = array('#X#', '#X_no_s#');
				$replace = array(strtoupper($m->name), ucfirst($m->name));
				
				$defaultViewEdit[] = str_replace(' ', '_', strtolower($m->name));
				
				$languageContent = LanguageHelper::getFormMessages();
				
				$languageContent = str_replace($search, $replace, $languageContent);
				
				$this->createBackendLanguage($languageContent);
			}
		}
		
		/**
		 * set default view
		 */
		if(empty($defaultView))
			$defaultView[0] = '';
		
		if(empty($defaultViewEdit))
			$defaultViewEdit[0] = '';
		
		//get backend language description
		$languageContent = LanguageHelper::getDescription();
		
		//create backend language description
		$this->createBackendLanguage($languageContent);
		
		//create main helper
		self::createBackendHelper();
		
		//set content to empty
		$content = '';
		
		//TODO CREATE MAIN CONTROLLER
		$content = self::getFileContent('controller.txt');
		
		$comName = str_replace(' ', '_', strtolower($component->name));		
		
		$search = array('#xs#', '#author#', '#to_copy#', '#component_prefix#', '#X_with_s#', '#TO_COPY#', '#XS#');
		$replace = array($defaultView[0], $component->author, $comName, $componentPrefix, ucfirst($defaultView[0]), strtoupper($comName), strtoupper($defaultView[0]));			
		
		$content = str_replace($search, $replace, $content);
		
		$file = $this->rootPath . DS . 'admin' . DS . 'controller.php';
		file_put_contents($file, $content);		
		//END CREATE MAIN CONTROLLER
		
		/**
		 * create main file, include controllers, xml to install ...
		 */
		$this->createMainFile();
		
		//generate front files
		self::generateFrontFiles();
		
		//create sql file
		$this->createSql();
		
		//package helper
		require_once 'joomla.packager.php';
		
		//generate index.html to all folder
		$genIndex = JoomlaPackager::genIndexFile(rtrim($this->rootPath, DS));
		
		//var_dump($this->rootPath); die;
		
		//zip file
		$zip = JoomlaPackager::zip(rtrim($this->rootPath, DS));
		
		return $comName;
	}
	
	/**
	 * This function to generate front files
	 */
	function generateFrontFiles()
	{
		$db = JFactory::getDbo();
		$component = $this->component;
		
		//process to get component prefix
		$componentPrefix = str_replace(' ', '_', ucwords($component->name));
		$comName = str_replace(' ', '_', strtolower($component->name));
		
		//get front models
		$query = $db->getQuery(true);
		
		$query->select('m.*, t.name AS table_name');
		$query->from('#__gencode_genmfronts m');
		
		$query->join('INNER', '#__gencode_gendbs t ON m.table_id = t.id');
		
		$query->where('m.state >= 0 AND m.component_id = ' . $component->id);
		
		$db->setQuery($query);
		$rs = $db->loadObjectList();
		$defaultView = array();
		if($rs)
		{
			foreach ($rs as $key => $m)
			{
				$type 		= $m->type;
				
				if($type == 'list')
					$defaultView[] = $filename = str_replace(' ', '_', strtolower($m->name));
				
				//create models
				self::createFrontModel($m, $type);
				
				//gemerate front views
				self::createFrontView($m, $type);
			}				
		}
		
		if(empty($defaultView))
			$defaultView[0] = '';
			
		
		//front controller
		$search = array('#xs#', '#author#', '#to_copy#', '#component_prefix#', '#X_with_s#', '#TO_COPY#', '#XS#');
		$replace = array($defaultView[0], $component->author, $comName, $componentPrefix, ucfirst($defaultView[0]), strtoupper($comName), strtoupper($defaultView[0]));
		
		$content = self::getFileContent('frontend' . DS . 'controller.txt');
		$content = str_replace($search, $replace, $content);
		
		$file = $this->rootPath . DS . 'site' . DS . 'controller.php';
		file_put_contents($file, $content);
	}
	
	/**
	 * Function to create front models
	 * @param Object $model
	 * @param String $type
	 */
	function createFrontModel($model, $type)
	{
		$root = $this->rootPath . DS . 'site' . DS;
		$component = $this->component;
	
		//process to get component prefix
		$componentPrefix = str_replace(' ', '_', ucwords($component->name));
	
		$filename = str_replace(' ', '_', strtolower($model->name));
		$comName = str_replace(' ', '_', strtolower($component->name));
	
		$content = null;
	
		$modelFormName 	= null;
		$search 		= array();
		$replace 		= array();
	
		if(is_object($model))
			$modelFormName = str_replace(' ', '_', strtolower($model->name));
		
		if($type == 'list')
			$content = self::getFileContent('frontend' . DS . 'models' . DS . 'xs.txt');
		else
			$content = self::getFileContent('frontend' . DS . 'models' . DS . 'x.txt');
		
		require_once 'create.front.model.php';
		$frontModel = new CreateFrontModel($model);
		
		$content = $frontModel->create($content, $filename, $component);
	
		$file = $root . 'models' . DS . $filename . '.php';
		file_put_contents($file, $content);
	}
	
	/**
	 * This function to create front view
	 * @param Object $model
	 * @param String $type
	 */
	function createFrontView($model, $type)
	{
		$root = $this->rootPath . DS . 'site' . DS;
		$component = $this->component;
		
		//process to get component prefix
		$componentPrefix = str_replace(' ', '_', ucwords($component->name));	
		
		$filename = str_replace(' ', '_', strtolower($model->name));
		$comName = str_replace(' ', '_', strtolower($component->name));
		
		$content = null;
		
		$modelFormName 	= null;
		$search 		= array();
		$replace 		= array();
		
		if(is_object($model))
			$modelFormName = str_replace(' ', '_', strtolower($model->name));
		
		//var_dump($model);
		
		/**
		 * Define folder for view
		 * @var String
		 */
		$viewDir = $root . 'views' . DS . $filename . DS;
		/**
		 * and template
		 * @var String
		 */
		$tmplDir = $root . 'views' . DS . $filename . DS . 'tmpl' . DS;
		
		/**
		 * make dir if not exist
		 */
		@mkdir($viewDir);
		@mkdir($tmplDir);
		
		$languageContent = '';
		
		if($type == 'list')
		{
			$content = self::getFileContent('frontend' . DS . 'views' . DS . 'xs' . DS . 'view.html.txt');
			$tmpl = self::getFileContent('frontend' . DS . 'views' . DS . 'xs' . DS . 'tmpl' . DS . 'default.txt');
			$xmlContent = self::getFileContent('frontend' . DS . 'views' . DS . 'xs' . DS . 'tmpl' . DS . 'default.xml.txt');			
			
			/**
			 * Set language for create menu
			 */
			$languageContent .= 'COM_#TO_COPY#_#XS#_VIEW_DEFAULT_TITLE="#X_with_s#"'."\n";
			$languageContent .= 'COM_#TO_COPY#_#XS#_VIEW_DEFAULT_OPTION="#X_with_s# Option"'."\n";
			$languageContent .= 'COM_#TO_COPY#_#XS#_VIEW_DEFAULT_DESC="#X_with_s# Description"'."\n";
			
			$search = array('#table#', '#xs#', '#author#', '#to_copy#', '#component_prefix#', '#X_with_s#', '#TO_COPY#', '#XS#', '#X_no_s#');
			$replace = array($model->table_name, $filename, $component->author, $comName, $componentPrefix, ucfirst($filename), strtoupper($comName), strtoupper($filename), ucfirst($modelFormName));			
			//echo '<pre>'; print_r($content); die;
		}
		else //if detail
		{
			$content = self::getFileContent('frontend' . DS . 'views' . DS . 'x' . DS . 'view.html.txt');
			$tmpl = self::getFileContent('frontend' . DS . 'views' . DS . 'x' . DS . 'tmpl' . DS . 'default.txt');
			$xmlContent = self::getFileContent('frontend' . DS . 'views' . DS . 'x' . DS . 'tmpl' . DS . 'default.xml.txt');
			
			/**
			 * Set language for create menu
			 */
			$languageContent .= 'COM_#TO_COPY#_#X#_VIEW_DEFAULT_TITLE="#X_no_s#"'."\n";
			$languageContent .= 'COM_#TO_COPY#_#X#_VIEW_DEFAULT_OPTION="#X_no_s# Option"'."\n";
			$languageContent .= 'COM_#TO_COPY#_#X#_VIEW_DEFAULT_DESC="#X_no_s# Description"'."\n";			
			
			$search = array('#x#', '#author#', '#to_copy#', '#component_prefix#', '#X_no_s#', '#TO_COPY#', '#X#');
			$replace = array($filename, $component->author, $comName, $componentPrefix, ucfirst($filename), strtoupper($comName), strtoupper($filename));
			//echo '<pre>'; print_r($content); die;
		}
		
		//get fields
		require_once 'create.front.model.php';
		$genmFields = CreateFrontModel::getFieldSelected($model->id);
		
		$genmFields = explode(',', str_replace(' ', '', $genmFields));
		
		$strContent = '';
		
		foreach ($genmFields as $genmField)
		{
			$tmpField = explode('.', $genmField);
		
			$strContent .= '
			<li>
			<?php echo \'<label>'.$tmpField[1].'</label>: \'. $this->escape($item->'.$tmpField[1].'); ?>
			</li>';
		}
		
		$joins = GenerateHelper::getRecord('#__gencode_genm_join', null, 'genm_id = ' . (int) $model->id);
		
		foreach ($joins as $key => $join)
		{
			$joinTable = $join->join_table;
			$tableAlias = $joinTable.'_'.$key;
		
			$listField = array();
			$fields = explode(',', str_replace(' ', '', $join->join_table_fields));
		
			if(!empty($fields))
			{
				foreach ($fields as $field)
				{
					if($field)
					{
						$field = $tableAlias . '_' . $field;
		
						$strContent .= '
						<li>
						<?php echo \'<label>\'.'.$field.'.\'</label>: \'. $this->escape($item->'.$field.'); ?>
						</li>';
					}
				}
			}
		}
		
		
		
		$searchTmpl[] = '#item_info#';
		$replaceTmpl[] = $strContent;
		
		$content 	= str_replace($search, $replace, $content);
		$tmpl 		= str_replace($search, $replace, $tmpl);
		$xmlContent = str_replace($search, $replace, $xmlContent);
		$languageContent = str_replace($search, $replace, $languageContent);
		
		$tmpl = str_replace($searchTmpl, $replaceTmpl, $tmpl);
		
		$fileTmpl 	= $tmplDir . DS . 'default.php';
		$fileXml 	= $tmplDir . DS . 'default.xml';
		$file 		= $root . 'views' . DS . $filename . DS . 'view.html.php';
		
		file_put_contents($file, 		$content	);
		file_put_contents($fileTmpl, 	$tmpl		);
		file_put_contents($fileXml, 	$xmlContent	);
		
		//update language
		$this->createSysBackendLanguage($languageContent);
	}
	
	/**
	 * Function to get record or list of records
	 * @param String $table 	Table name
	 * @param Int $id			ID to get
	 * @param Bool $where		If $where is true, will get record
	 * @return Object Record or List of record
	 */
	function getRecord($table, $id, $where = null)
	{
		$db 	= JFactory::getDbo();
		$query 	= $db->getQuery(true);
		
		$query->select('*');
		$query->from($table);
		
		//var_dump(func_get_args());
		
		if(!$where)
			$where = 'id = ' . (int) $id;
		
		$query->where($where);
		
		//echo $query;
		
		$db->setQuery($query);
		
		if($id)
			$rec = $db->loadObject();
		else 
			$rec = $db->loadObjectList();
		
		return $rec;
	}
	
	/**
	 * Function to get content of file from template: com_to_copy
	 * @param String $file	File name
	 */
	public function getFileContent($file)
	{
		//path to component template
		$path = JPATH_COMPONENT_ADMINISTRATOR . DS . 'helpers' . DS . 'com_to_copy' . DS;
		
		$content = file_get_contents($path . $file);
		
		return $content;
	}
	
	/**
	 * Create Backend controller
	 * @param String $name			Controller name
	 * @param String $type			List or Form
	 * @param Object $modelForm		Model object
	 */
	protected function createBackendController($name, $type, $modelForm = null)
	{
		$root = $this->rootPath . DS . 'admin' . DS;
		$component = $this->component;
		
		//process to get component prefix
		$componentPrefix = str_replace(' ', '_', ucwords($component->name));	
		
		$filename = str_replace(' ', '_', strtolower($name));
		$comName = str_replace(' ', '_', strtolower($component->name));
		
		$content = null;
		
		$modelFormName 	= null;
		$search 		= array();
		$replace 		= array();
		
		$content = '';
		
		if(is_object($modelForm))
			$modelFormName = str_replace(' ', '_', strtolower($modelForm->name));
		
		if($type == 'list')
		{
			$content = self::getFileContent('controllers' . DS . 'xs.txt');
			
			$search = array('#xs#', '#author#', '#to_copy#', '#component_prefix#', '#X_with_s#', '#TO_COPY#', '#XS#', '#X_no_s#');
			$replace = array($filename, $component->author, $comName, $componentPrefix, ucfirst($filename), strtoupper($comName), strtoupper($filename), ucfirst($modelFormName));			
		}
		else //if form
		{
			$content = self::getFileContent('controllers' . DS . 'x.txt');
			
			$search = array('#x#', '#author#', '#to_copy#', '#component_prefix#', '#X_no_s#', '#TO_COPY#', '#X#');
			$replace = array($filename, $component->author, $comName, $componentPrefix, ucfirst($filename), strtoupper($comName), strtoupper($filename));			
		}
		
		$content = str_replace($search, $replace, $content);
		
		$file = $root . 'controllers' . DS . $filename . '.php';
		file_put_contents($file, $content);
	}
	
	/**
	 * Create model in backend
	 * @param Object $model	Model object
	 * @param String $type	List or form
	 */
	function createBackendModel($model, $type)
	{
		$root = $this->rootPath . DS . 'admin' . DS;
		$component = $this->component;
		
		//process to get component prefix
		$componentPrefix = str_replace(' ', '_', ucwords($component->name));	
		
		$filename = str_replace(' ', '_', strtolower($model->name));
		$comName = str_replace(' ', '_', strtolower($component->name));
		
		$content = null;
		
		$modelFormName 	= null;
		$search 		= array();
		$replace 		= array();
		
		if(is_object($model))
			$modelFormName = str_replace(' ', '_', strtolower($model->name));
		
		//var_dump($model);
		
		if($type == 'list')
		{
			$content = self::getFileContent('models' . DS . 'xs.txt');
			
			require_once 'create.backend.model.list.php';
			$modelList = new CreateBackendModelList($model);
			
			$content = $modelList->create($content, $filename, $component);
			
			//echo '<pre>'; print_r($content); die;
		}
		else //if form
		{
			$content = self::getFileContent('models' . DS . 'x.txt');
			
			require_once 'create.backend.model.edit.php';
			$modelEdit = new CreateBackendModelEdit($model);
			
			$content = $modelEdit->create($content, $filename, $component);
			
			//create table
			$this->createTable($root, $model, $filename, $component);
			
			//create xml file
			$this->createBackendXmlFile($root, $model, $filename, $component);
			
			//echo '<pre>'; print_r($content); die;
		}
				
		$file = $root . 'models' . DS . $filename . '.php';
		file_put_contents($file, $content);
	}
	
	/**
	 * Create xml file in backend
	 * @param String $root		Path to root
	 * @param Object $model		Model object
	 * @param String $filename	File name
	 */
	function createBackendXmlFile($root, $model, $filename)
	{
		$component = $this->component;
		
		$content = self::getFileContent('models' . DS . 'forms' . DS . 'x.txt');
		
		$comName = str_replace(' ', '_', strtolower($component->name));
		$componentPrefix = str_replace(' ', '_', ucwords($component->name));
		
		$search = array('#table#', '#x#', '#author#', '#to_copy#', '#component_prefix#', '#X_no_s#', '#TO_COPY#', '#X#');
		$replace = array($model->table_name, $filename, $component->author, $comName, $componentPrefix, ucfirst($filename), strtoupper($comName), strtoupper($filename));
		
		//get form fields
		$fields = $this->getFormFields($model->id);
		
		//require xml helper to gen field
		require_once 'build.xml.helper.php';		
		$xml = new BuildXmlHelperClass($root);
		
		$str = '';
		
		//var_dump($fields);
		
		foreach ($fields as $field)
		{
			$str .= $xml->createField($component, $field);
		}
		
		$search[] = '#XML_DEFINE_FIELD_STRING#';
		$replace[] = $str;
		
		//var_dump($str); die;
		
		$content = str_replace($search, $replace, $content);
		
		$file = $root . 'models' . DS . 'forms' . DS . $filename . '.xml';
		file_put_contents($file, $content);
	}
	
	/**
	 * Get ffields were selected in form
	 * @param Int $modelId Model ID
	 * @return List of fields object, include params
	 */
	function getFormFields($modelId)
	{
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);
		
		$query->select('*');
		$query->from('#__gencode_genm_form_fields');
		$query->where('genm_id = ' . (int) $modelId);
		
		$db->setQuery($query);
		
		$rs = $db->loadObjectList();
		
		foreach ($rs as & $r)
		{
			$tmp = unserialize($r->params);
			$r->params = $tmp;
		}
		
		return $rs;
	}
	
	/**
	 * Create views in backend
	 * @param Object $model		Model object
	 * @param String $type		List or edit
	 */
	function createBackendView($model, $type)
	{
		$root = $this->rootPath . DS . 'admin' . DS;
		$component = $this->component;
		
		//process to get component prefix
		$componentPrefix = str_replace(' ', '_', ucwords($component->name));	
		
		$filename = str_replace(' ', '_', strtolower($model->name));
		$comName = str_replace(' ', '_', strtolower($component->name));
		
		$content = null;
		
		$modelFormName 	= null;
		$search 		= array();
		$replace 		= array();
		
		if(is_object($model))
		{
			$modelFormName = str_replace(' ', '_', strtolower($model->name));
			$modelFormJoinName = str_replace(' ', '_', strtolower($model->model_form_name));
		}
				
		//var_dump($model);
		
		$viewDir = $root . 'views' . DS . $filename . DS;
		$tmplDir = $root . 'views' . DS . $filename . DS . 'tmpl' . DS;
		
		@mkdir($viewDir);
		@mkdir($tmplDir);
		
		if($type == 'list')
		{
			$languageContent = '';
			
			$content = self::getFileContent('views' . DS . 'xs' . DS . 'view.html.txt');
			$tmpl = self::getFileContent('views' . DS . 'xs' . DS . 'tmpl' . DS . 'default.txt');
			
			$search = array('#table#', '#xs#', '#author#', '#to_copy#', '#component_prefix#', '#X_with_s#', '#TO_COPY#', '#XS#', '#X_no_s#', '#x#');
			$replace = array($model->table_name, $filename, $component->author, $comName, $componentPrefix, ucfirst($filename), strtoupper($comName), strtoupper($filename), ucfirst($modelFormName), $modelFormJoinName);
			
			//get filter
			$filter = unserialize($model->fields_to_filter);
			
			$strFilter = '';
			
			/**
			 * Set filter
			 */
			if(isset($filter['state']))
			{
				$strFilter .= '
					<select name="filter_state" class="inputbox" onchange="this.form.submit()">
						<option value=""><?php echo JText::_(\'JOPTION_SELECT_PUBLISHED\');?></option>
						<?php echo JHtml::_(\'select.options\', JHtml::_(\'jgrid.publishedOptions\'), \'value\', \'text\', $this->state->get(\'filter.state\'), true);?>
					</select>';
			}
			
			if(isset($filter['category']))
			{
				$strFilter .= '
					<select name="filter_category_id" class="inputbox" onchange="this.form.submit()">
						<option value=""><?php echo JText::_(\'JOPTION_SELECT_CATEGORY\');?></option>
						<?php echo JHtml::_(\'select.options\', JHtml::_(\'category.options\', \'com_'.$comName.'\'), \'value\', \'text\', $this->state->get(\'filter.category_id\'));?>
					</select>';
			}
			
			if(isset($filter['language']))
			{
				$strFilter .= '
					<select name="filter_language" class="inputbox" onchange="this.form.submit()">
						<option value=""><?php echo JText::_(\'JOPTION_SELECT_LANGUAGE\');?></option>
						<?php echo JHtml::_(\'select.options\', JHtml::_(\'contentlanguage.existing\', true, true), \'value\', \'text\', $this->state->get(\'filter.language\'));?>
					</select>';
			}
			
			if(isset($filter['created_by']))
			{
				$strFilter .= '
					<select name="filter_author_id" class="inputbox" onchange="this.form.submit()">
						<option value=""><?php echo JText::_(\'JOPTION_SELECT_AUTHOR\');?></option>
						<?php echo JHtml::_(\'select.options\', $this->authors, \'value\', \'text\', $this->state->get(\'filter.author_id\'));?>
					</select>';
				
				$search[] = '#GET_AUTHOR#';
				$replace[] = '$this->authors		= $this->get(\'Authors\');';
			}
			else 
			{
				$search[] = '#GET_AUTHOR#';
				$replace[] = '';
			}
			
			$searchTmpl = array('#FILTER_STRING#');
			$replaceTmpl = array($strFilter);
			
			//get fields
			require_once 'create.backend.model.list.php';
			$genmFields = CreateBackendModelList::getFieldSelected($model->id);
			
			$genmFields = explode(',', str_replace(' ', '', $genmFields));
			
			$strColumnsHeader = '';
			$strColumnsContent = '';
			
			/**
			 * Create heading
			 */
			foreach ($genmFields as $genmField)
			{
				$tmpField = explode('.', $genmField);
				
				$strColumnsHeader .= '
				<th>
					<?php echo JHtml::_(\'grid.sort\',  \'COM_'.strtoupper($comName).'_HEADING_'.strtoupper($tmpField[1]).'\', \''.$genmField.'\', $listDirn, $listOrder); ?>
				</th>';
				
				$strColumnsContent .= '
				<td class="center">
					<?php echo $this->escape($item->'.$tmpField[1].'); ?>
				</td>';
				
				//create header language
				$searchLang = array('#FIELD_HEADING#', '#Field_Heading#');
				$replaceLang = array(strtoupper($tmpField[1]), ucfirst(str_replace('_', ' ', $tmpField[1])));
				
				$languageContent = str_replace($searchLang, $replaceLang, LanguageHelper::getHeading());
				
				$this->createBackendLanguage($languageContent);
				/* end create language */
			}
			
			$joins = GenerateHelper::getRecord('#__gencode_genm_join', null, 'genm_id = ' . (int) $model->id);
			
			/**
			 * More heading from join tables
			 */
			foreach ($joins as $key => $join)
			{
				$joinTable = $join->join_table;
				$tableAlias = $joinTable.'_'.$key;
				
				$listField = array();
				$fields = explode(',', str_replace(' ', '', $join->join_table_fields));
				
				if(!empty($fields))
				{
					foreach ($fields as $field)
					{
						if($field)
						{
							$field = $tableAlias . '_' . $field;
							
							$strColumnsHeader .= '
				<th>
					<?php echo JHtml::_(\'grid.sort\',  \'COM_'.strtoupper($comName).'_HEADING_'.strtoupper($field).'\', \''.$field.'\', $listDirn, $listOrder); ?>
				</th>';
							
							$strColumnsContent .= '
				<td class="center">
					<?php echo $this->escape($item->'.$field.'); ?>
				</td>';
							//create header language
							$searchLang = array('#FIELD_HEADING#', '#Field_Heading#');
							$replaceLang = array(strtoupper($field), ucfirst(str_replace('_', ' ', $field)));
							
							$languageContent = str_replace($searchLang, $replaceLang, LanguageHelper::getHeading());
							$this->createBackendLanguage($languageContent);
							/* end create language */
						}
					}
				}
			}
			
			/**
			 * Replace heading content
			 */
			$searchTmpl[] = '#COLUMNS_HEADER#';
			$replaceTmpl[] = $strColumnsHeader;
			
			/**
			 * Replace content
			 */
			$searchTmpl[] = '#COLUMNS_CONTENT#';
			$replaceTmpl[] = $strColumnsContent;
			
			$content = str_replace($search, $replace, $content);
			$tmpl = str_replace($search, $replace, $tmpl);
			
			$tmpl = str_replace($searchTmpl, $replaceTmpl, $tmpl);
			
			$fileTmpl = $tmplDir . DS . 'default.php';
			//echo '<pre>'; print_r($content); die;
		}
		else //if form
		{
			$content = self::getFileContent('views' . DS . 'x' . DS . 'view.html.txt');
			$tmpl = self::getFileContent('views' . DS . 'x' . DS . 'tmpl' . DS . 'edit.txt');
			
			$search = array('#x#', '#author#', '#to_copy#', '#component_prefix#', '#X_no_s#', '#TO_COPY#', '#X#');
			$replace = array($filename, $component->author, $comName, $componentPrefix, ucfirst($filename), strtoupper($comName), strtoupper($filename));
			
			//get form fields
			$fields = $this->getFormFields($model->id);
			
			$strGetFormFields = '';
			
			/**
			 * Build field in edit form
			 */
			foreach ($fields as $field)
			{
				$strGetFormFields .= '
				<li><?php echo $this->form->getLabel(\''.$field->field_name.'\'); ?>
				<?php echo $this->form->getInput(\''.$field->field_name.'\'); ?></li>
				';
				
				//create text for form field
				$searchLang = array('#FIELD_NAME#', '#Field_Name#');
				$replaceLang = array(strtoupper($field->field_name), ucfirst($field->field_name));
				
				$languageContent = str_replace($searchLang, $replaceLang, LanguageHelper::getTextField());
				
				$this->createBackendLanguage($languageContent);
				/* end create language */
			}
			
			/**
			 * Replace content
			 */
			$searchTmpl = array('#GET_FORM_FIELDS#');
			$replaceTmpl = array($strGetFormFields);
			
			$content = str_replace($search, $replace, $content);
			
			$tmpl = str_replace($search, $replace, $tmpl);
			$tmpl = str_replace($searchTmpl, $replaceTmpl, $tmpl);
			
			$fileTmpl = $root . 'views' . DS . $filename . DS . 'tmpl' . DS . 'edit.php';
			//echo '<pre>'; print_r($content); die;
		}
				
		$file = $root . 'views' . DS . $filename . DS . 'view.html.php';
		
		file_put_contents($file, $content);
		file_put_contents($fileTmpl, $tmpl);
	}
	
	/**
	 * Create tables
	 * @param String $root		Path to root
	 * @param Object $model		Model object
	 * @param String $filename	File name
	 */
	function createTable($root, $model, $filename)
	{
		$component = $this->component;
		
		$content = self::getFileContent('tables' . DS . 'x.txt');
		
		$comName = str_replace(' ', '_', strtolower($component->name));
		$componentPrefix = str_replace(' ', '_', ucwords($component->name));
		
		$search = array('#table#', '#x#', '#author#', '#to_copy#', '#component_prefix#', '#X_no_s#', '#TO_COPY#', '#X#');
		$replace = array($model->table_name, $filename, $component->author, $comName, $componentPrefix, ucfirst($filename), strtoupper($comName), strtoupper($filename));
		
		//get filter
		$filter = unserialize($model->fields_to_filter);
		
		if(isset($filter['category']) && $filter['category'])
		{
			$catId = $filter['catid'];
			
			$search[] = '#CATEGORY_ORDER_CONDITION#';
			$replace[] = '|| $oldrow->'.$catId.' != $this->'.$catId;
			
			$search[] = '#CATEGORY_ORDER_CONDITION_STRING#';
			$replace[] = '`'.$catId.'`=\' . $this->_db->Quote($this->'.$catId.').\' AND';
			
			$search[] = '#CHECK_ALIAS_WITH_CATEGORY_ID#';			
			$replace[] = ',\''.$catId.'\'=>$this->'.$catId;
		}
		else
		{
			$search[] = '#CATEGORY_ORDER_CONDITION#';
			$replace[] = '';
			
			$search[] = '#CATEGORY_ORDER_CONDITION_STRING#';			
			$replace[] = '';
			
			$search[] = '#CHECK_ALIAS_WITH_CATEGORY_ID#';			
			$replace[] = '';
		}
		
		$content = str_replace($search, $replace, $content);
		
		$file = $root . 'tables' . DS . $filename . '.php';
		file_put_contents($file, $content);
	}
	
	/**
	 * Create helper
	 */
	function createBackendHelper()
	{
		$root = $this->rootPath . DS . 'admin' . DS;
		$component = $this->component;
		
		$content = self::getFileContent('helpers' . DS . 'to_copy.txt');
		
		$comName = str_replace(' ', '_', strtolower($component->name));
		$componentPrefix = str_replace(' ', '_', ucwords($component->name));
		
		$search = array('#author#', '#to_copy#', '#component_prefix#', '#TO_COPY#');
		$replace = array($component->author, $comName, $componentPrefix, strtoupper($comName));
		
		//get list of models (type = list)
		$db = JFactory::getDbo();
		$query = $db->getQuery(true);
		
		$query->select('*');
		$query->from('#__gencode_genms');
		$query->where('component_id = ' . (int) $component->id . ' AND type = "list"');
		
		$db->setQuery($query);
		
		$listModels = $db->loadObjectList();
		
		$strMenu = '';
		
		foreach ($listModels as $model)
		{
			$vName = str_replace(' ', '_', strtolower($model->name));
			
			$strMenu .= '
			JSubMenuHelper::addEntry(
				JText::_(\'COM_'.strtoupper($comName).'_SUBMENU_'.strtoupper($vName).'\'),
				\'index.php?option=com_'.$comName.'&view='.$vName.'\',
				$vName == \''.$vName.'\'
			);';
		}
		
		$search[] = '#MENU_STRING#';
		$replace[] = $strMenu;
		
		$strMenuCategory = '';
		
		/**
		 * if set create menu when create component, then create sub menu Categories
		 */
		if($component->create_sub_menu_category)
		{
			$strMenuCategory = '
			JSubMenuHelper::addEntry(
				JText::_(\'COM_'.strtoupper($comName).'_SUBMENU_CATEGORIES\'),
				\'index.php?option=com_categories&extension=com_'.$comName.'\',
				$vName == \'categories\'
			);
			if ($vName==\'categories\') {
				JToolBarHelper::title(
					JText::sprintf(\'COM_CATEGORIES_CATEGORIES_TITLE\',JText::_(\'com_'.$comName.'\')),
					\''.$comName.'\');
			}';
		}
		
		/**
		 * Replace content
		 */
		$search[] = '#MENU_CATEGORY#';
		$replace[] = $strMenuCategory;
		
		$content = str_replace($search, $replace, $content);
		
		$file = $root . 'helpers' . DS . $comName . '.php';
		file_put_contents($file, $content);
	}
	
	/**
	 * Create Language
	 * @param String $content	Language content
	 * @param Bool $update		If update true, added language to langue file, else, get content from template
	 */
	function createBackendLanguage($content = '', $update = true)
	{
		$flag = ($update) ? FILE_APPEND : null;
		
		$root = $this->rootPath . DS . 'admin' . DS;
		$component = $this->component;
		
		$comName = str_replace(' ', '_', strtolower($component->name));
		$componentPrefix = str_replace(' ', '_', ucwords($component->name));
		
		$search = array('#author#', '#to_copy#', '#component_prefix#', '#TO_COPY#', '#component_name#', '#component_description#');
		$replace = array($component->author, $comName, $componentPrefix, strtoupper($comName), $component->name, $component->description);
		
		if(!$update)
			$content = self::getFileContent('languages' . DS . 'en-GB.com_to_copy.txt');
		
		$content = str_replace($search, $replace, $content);
		
		$file = $root . 'language' . DS . 'en-GB.com_' . $comName . '.ini';
		file_put_contents($file, $content, $flag);
	}
	
	/**
	 * Create Sys Language in backend
	 * @param String $content	Language content
	 * @param Bool $update		If update true, added language to langue file, else, get content from template
	 */
	function createSysBackendLanguage($content = '', $update = true)
	{
		$flag = ($update) ? FILE_APPEND : null;
		
		$root = $this->rootPath . DS . 'admin' . DS;
		$component = $this->component;
		
		$comName = str_replace(' ', '_', strtolower($component->name));
		$componentPrefix = str_replace(' ', '_', ucwords($component->name));
		
		$search = array('#author#', '#to_copy#', '#component_prefix#', '#TO_COPY#', '#component_name#', '#component_description#');
		$replace = array($component->author, $comName, $componentPrefix, strtoupper($comName), $component->name, $component->description);
		
		if(!$update)
			$content = self::getFileContent('languages' . DS . 'en-GB.com_to_copy.sys.txt');
		
		$content = str_replace($search, $replace, $content);
		
		$file = $root . 'language' . DS . 'en-GB.com_' . $comName . '.sys.ini';
		file_put_contents($file, $content, $flag);
	}
	
	/**
	 * Create main controller, file to run, config, access
	 */
	function createMainFile()
	{
		$root = $this->rootPath . DS . 'admin' . DS;
		$rootFront = $this->rootPath . DS . 'site' . DS;
		
		$component = $this->component;
		
		$comName = str_replace(' ', '_', strtolower($component->name));
		$componentPrefix = str_replace(' ', '_', ucwords($component->name));
		
		$search = array('#author#', '#to_copy#', '#component_prefix#', '#TO_COPY#', '#component_name#', '#component_description#');
		$replace = array($component->author, $comName, $componentPrefix, strtoupper($comName), $component->name, $component->description);
		
		$content = self::getFileContent('to_copy.txt');
		
		$content = str_replace($search, $replace, $content);
		
		$file = $root . $comName . '.php';
		file_put_contents($file, $content);
		
		$content = self::getFileContent('config.txt');
		
		$content = str_replace($search, $replace, $content);
		
		$file = $root . 'config.xml';
		file_put_contents($file, $content);
		
		$content = self::getFileContent('access.txt');
		
		$content = str_replace($search, $replace, $content);
		
		$file = $root . 'access.xml';
		file_put_contents($file, $content);
		
		$content = self::getFileContent('to_copy.xml.txt');
		
		$content = str_replace($search, $replace, $content);
		
		$file = $this->rootPath . $comName . '.xml';
		file_put_contents($file, $content);
		
		/* frontend */
		
		//main file
		$content = self::getFileContent('frontend' . DS . 'to_copy.txt');
		
		$content = str_replace($search, $replace, $content);
		
		$file = $rootFront . $comName . '.php';
		file_put_contents($file, $content);
		
		//metadata
		$content = self::getFileContent('frontend' . DS . 'metadata.xml.txt');
		$content = str_replace($search, $replace, $content);
		
		$file = $rootFront . 'metadata.xml';
		file_put_contents($file, $content);
	}
	
	/**
	 * Get talbe in component
	 * @param Int $componentId	Component id
	 * @return List of table objects
	 */
	function getTables($componentId)
	{
		$db = JFactory::getDbo();
		
		$query = $db->getQuery(true);
		
		$query->select('*');
		$query->from('#__gencode_gendbs');
		$query->where('component_id = ' . (int) $componentId);
		
		$db->setQuery($query);
		$tables = $db->loadObjectList();
		
		return $tables;
	}
	
	/**
	 * Get fields in table
	 * @param Int $tableId	Table ID
	 * @return List of field objects
	 */
	function getTableFields($tableId)
	{
		$db = JFactory::getDbo();
	
		$query = $db->getQuery(true);
	
		$query->select('*');
		$query->from('#__gencode_fields');
		$query->where('gendb_id = ' . (int) $tableId);
	
		$db->setQuery($query);
		$fields = $db->loadObjectList();
	
		return $fields;
	}
	
	/**
	 * Create sql file, contain sql to install and saved in sql folder
	 */
	function createSql()
	{
		//required table options
		require_once 'tableoptions.helper.class.php';
		
		$component = $this->component;
		
		$tables = $this->getTables($component->id);
		
		$sql = '';
		$sqlUninstall = '';
		
		//$stringType = array('CHAR','VARCHAR', 'TINYTEXT', 'TEXT', 'MEDIUMTEXT', 'LONGTEXT');
		
		foreach ($tables as $table)
		{
			$sqlUninstall .= 'DROP TABLE IF EXISTS `#__'.$table->name.'`
';
			$sql .= '
CREATE TABLE IF NOT EXISTS `#__'.$table->name.'` (
  `id` INTEGER NOT NULL AUTO_INCREMENT,
';
			
			$fields = $this->getTableFields($table->id);
			
			foreach ($fields as $field)
			{
				$sql .= '  `'.$field->name.'` '.$field->type;
				
				if($field->length)
					$sql .= '('.$field->length.') ';
				
				/*
				if(in_array($field->type, $stringType))
				{
					$tmp = explode('_', $field->collation);
					
					if(!$tmp[0])
						$tmp[0] = 'utf8';
					
					if(!$field->collation)
						$field->collation = 'utf8_general_ci';
						
					$sql .= ' CHARACTER SET '.$tmp[0].' COLLATE '.$field->collation;
				}
				*/
				
				if($field->attributes)
					$sql .= $field->attributes;
				
				if(!$field->is_null)
					$sql .= ' NOT NULL ';
				
				if($field->default_value)
					$sql .= ' DEFAULT ' . $field->default_value;
				
				if($field->comment)
					$sql .= ' COMMENT \'' . $field->default_value . '\'';
					
				$sql .= ',
';
			}
			
			if($table->collation)
				$tmp = explode('_', $table->collation);
			else
				$tmp = array('utf8');
			
  
			$sql .= '  `state` TINYINT(3) NOT NULL DEFAULT \'0\',
  `ordering` INTEGER NOT NULL DEFAULT \'0\',
  `metakey` TEXT NOT NULL,
  `metadesc` text NOT NULL,
  `created` datetime NOT NULL DEFAULT \'0000-00-00 00:00:00\',
  `created_by` int(10) unsigned NOT NULL DEFAULT \'0\',
  `modified` datetime NOT NULL DEFAULT \'0000-00-00 00:00:00\',
  `modified_by` int(10) unsigned NOT NULL DEFAULT \'0\',
  `checked_out` int(10) unsigned NOT NULL DEFAULT \'0\',
  `checked_out_time` datetime NOT NULL DEFAULT \'0000-00-00 00:00:00\',
  `publish_up` datetime NOT NULL DEFAULT \'0000-00-00 00:00:00\',
  `publish_down` datetime NOT NULL DEFAULT \'0000-00-00 00:00:00\',
  `language` char(7) NOT NULL DEFAULT \'\',
  PRIMARY KEY  (`id`)
) ENGINE='.$table->storage_engine.' DEFAULT CHARSET='.$tmp[0].' COMMENT=\''.$table->comment.'\';
';

		}
		
		$root = $this->rootPath . DS . 'admin' . DS;
		
		$file = $root . 'sql' . DS . 'install.mysql.utf8.sql';
		file_put_contents($file, $sql);
		
		$file = $root . 'sql' . DS . 'uninstall.mysql.utf8.sql';
		file_put_contents($file, $sqlUninstall);
	}
}